package com.ybkj.daijia.api.driver.v4;

import com.google.gson.Gson;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.common.HtmlHelper;
import com.ybkj.daijia.server.Config;
import com.ybkj.daijia.server.model.AreaOfEmploy;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverLogin;
import com.ybkj.daijia.server.service.AreaOfEmployService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverLoginService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.OrderService;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 司机地区相关
 *
 * @author bo
 */
@Controller("AreaControllerV4")
@RequestMapping(value = "driver/api/rest/v4")
public class AreaController {

    private static final Logger logger = LoggerFactory.getLogger(AreaController.class);

    @Autowired
    private DriverService driverService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private DriverLoginService driverLoginService;
    @Autowired
    private AreaOfEmployService areaOfEmployService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SettingUtils settingUtils;


    /**
     * 查询地区信息
     */
    @RequestMapping("areaDetail/{driverId}")
    public ModelAndView areaDetail(@PathVariable("driverId") Long driverId) {

        ModelAndView mv = new ModelAndView();

        Driver driver = driverService.findOne(driverId);
        Company company = companyService.findOne(driver.getCompanyId());

        mv.addObject("cityName", company.getCityName());
        mv.addObject("feeContent", HtmlHelper.htmlscripttext(company.getFeeContent()));

        mv.setViewName("area/view");

        return mv;
    }

    /**
     * 查询地区信息(过APP测评)
     */
    @RequestMapping("areaDetail2/{driverId}")
    public @ResponseBody
    ResultTransport areaDetail2(@PathVariable("driverId") Long driverId,
        HttpServletRequest request) {

        Driver driver = driverService.findOne(driverId);
        Company company = companyService.findOne(driver.getCompanyId());

        try {
            String path = String.format("%s/WEB-INF/views/area/", Config.getWebapp());

            Configuration cfg = new Configuration();

            cfg.setTemplateLoader(new FileTemplateLoader(new File(path)));
            cfg.setDefaultEncoding("UTF-8");

            Template template = cfg.getTemplate("view2.ftl");

            Map<String, Object> root = new HashMap<String, Object>();
            root.put("ctx", request.getContextPath());
            root.put("cityName", company.getCityName());
            root.put("feeContent", HtmlHelper.htmlscripttext(company.getFeeContent()));

            StringWriter writer = new StringWriter();
            template.process(root, writer);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            Map<String, String> datamap = new HashMap<String, String>();
            datamap.put("content", HtmlHelper.replaceBlank(writer.toString()));
            instance.setData(datamap);
            return instance;

        } catch (IOException e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        } catch (TemplateException e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }


    @RequestMapping(value = "listMyArea", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport listMyArea(String employToken) {

        logger.debug("recv employToken:{}", employToken);

        if (StringUtils.isBlank(employToken)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        Company company = companyService.findOne(driver.getCompanyId());

        if (!company.getAllowPayRule()) {//允许司机自行设置收费标准
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_ALLOW_PAYRULE);
        }

        try {

            List<AreaOfEmploy> myAreas = areaOfEmployService.findByEmployWithCharge(driver.getId());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(myAreas);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver listMyArea error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "saveMyArea", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport saveMyArea(String area, String employToken) {

        logger.debug("recv employToken:{},area:{}", employToken, area);

        if (StringUtils.isBlank(employToken) || StringUtils.isBlank(area)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        Company company = companyService.findOne(driver.getCompanyId());

        if (!company.getAllowPayRule()) {//允许司机自行设置收费标准
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_ALLOW_PAYRULE);
        }

        Gson gson = new Gson();
        AreaOfEmploy areaOfEmploy = gson.fromJson(area, AreaOfEmploy.class);

        areaOfEmploy.setEmployId(driver.getId());

        AreaOfEmploy old = areaOfEmployService
            .findByNameAndEmploy(areaOfEmploy.getName(), driver.getId());

        if (null != old) {
            return ResultTransport.getErrorBy(ErrorConstantV4.SAME_AREA_NAME_HAS_EXISTS_ERROR);
        }

        try {

            areaOfEmployService.save(areaOfEmploy);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver saveMyArea error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "updateMyArea", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport updateMyArea(String area, String employToken) {

        logger.debug("recv employToken:{},area:{}", employToken, area);

        if (StringUtils.isBlank(employToken) || StringUtils.isBlank(area)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        Company company = companyService.findOne(driver.getCompanyId());

        if (!company.getAllowPayRule()) {//允许司机自行设置收费标准
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_ALLOW_PAYRULE);
        }

        Gson gson = new Gson();
        AreaOfEmploy areaOfEmploy = gson.fromJson(area, AreaOfEmploy.class);

        areaOfEmploy.setEmployId(driver.getId());

        AreaOfEmploy old = areaOfEmployService
            .findByNameAndEmploy(areaOfEmploy.getName(), driver.getId());

        if (null != old) {
            if (!old.getId().equals(areaOfEmploy.getId())) {
                return ResultTransport.getErrorBy(ErrorConstantV4.SAME_AREA_NAME_HAS_EXISTS_ERROR);
            }
        }

        try {

            areaOfEmployService.update(areaOfEmploy);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver updateMyArea error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "deleteMyArea", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport deleteMyArea(Long areaId, String employToken) {

        logger.debug("recv employToken:{}", employToken);

        if (StringUtils.isBlank(employToken) || null == areaId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        Company company = companyService.findOne(driver.getCompanyId());

        if (!company.getAllowPayRule()) {//允许司机自行设置收费标准
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_ALLOW_PAYRULE);
        }

        try {

            areaOfEmployService.delete(areaId);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver deleteMyArea error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "getMyPrice", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport getMyPrice(String employToken, String phone, Integer time, Double mileage,
        Long areaId) {

        logger
            .debug("recv employToken:{},phone:{},time:{},mileage:{},areaId:{}", employToken, phone,
                time, mileage, areaId);

        if (StringUtils.isBlank(employToken) || null == time || null == mileage) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            Map<String, Object> map = orderService.getMyPrice(time, mileage, driver, phone, areaId);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(map);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver getMyPrice error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }
}
